#include <iostream>
#include <limits>
using std::cin;
using std::cout;
using std::endl;
using std::ostream;
using std::istream;

void inputInt(istream & ist,int & num){
    cout << "请输入一个int型数据" << endl;
    while(ist >> num, !ist.eof()){
        if(ist.bad()){
            cout << "istream has broken!" << endl;
            return;
        }else if(ist.fail()){
            ist.clear();
            ist.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
            cout << "看清楚一点，输入int型数据" << endl;
        }else{
            break;
        }
    }
}

class Complex
{
public:
    Complex(int real,int image)
    : _real(real)
    , _image(image)
    {}

    void print() const{
        cout << _real << " + "
            << _image << "i"
            << endl;
    }

    Complex & operator+=(const Complex & rhs){
        _real += rhs._real;
        _image += rhs._image;
        return *this;
    }

    Complex & operator++(){
        cout << "前置++函数" << endl;
        ++_real;
        ++_image;
        return *this;
    }

    Complex operator++(int){
        cout << "后置++函数" << endl;
        Complex temp(*this);
        ++_real;
        ++_image;
        return temp;
    }

    //这样重载的效果只能实现cx1 << cout
    //与内置类型的使用不一致
    /* ostream & operator<<(ostream & os){ */
    /*     os << _real << " + " << _image << "i"; */
    /*     return os; */
    /* } */


    friend Complex operator+(const Complex & c1,const Complex & c2);
    friend ostream & operator<<(ostream & os,const Complex & rhs);
    friend istream & operator>>(istream & is,Complex & rhs);
private:
    int _real;
    int _image;
};

Complex operator+(const Complex & c1,const Complex & c2)
{
    return Complex(c1._real + c2._real,
                   c1._image + c2._image);

}

ostream & operator<<(ostream & os,const Complex & rhs){
    os << rhs._real << " + " << rhs._image << "i";
    return os;
}


istream & operator>>(istream & is,Complex & rhs){
    cout << "请输入实部：" << endl;
    /* is >> rhs._real; */
    inputInt(is,rhs._real);
    cout << "请输入虚部：" << endl;
    /* is >> rhs._image; */
    inputInt(is,rhs._image);
    //链式输入无法处理错误输入的情况
    /* is >> rhs._real >> rhs._image; */
    return is;
}



void test0(){
    Complex cx1(1,2);
    //不再使用这种形式
    /* cx1.print(); */

    //cx1.operator<<(cout);
    /* cx1 << cout << endl; */

    //本质形式
    /* operator<<(cout,cx1) << endl; */
    cout << cx1 << endl;

    //operator>>(cin,cx1);
    cin >> cx1;
    cout << cx1 << endl;
}

void test1(){
    Complex cx1(1,2);
    Complex cx2(3,4);
    cx1 += cx2;
    cx1.operator+=(cx2);
}

int main(void){
    test0();
    return 0;
}
